package com.example.administrator.rxjavarxandroid_retrofit.http.factory;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.internal.http.RealResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by chenboge on 2016/12/15.
 */
public class ApiErrorAwareConverterFactory extends Converter.Factory {

    private final EmptyJsonLenientConverterFactory mEmptyJsonLenientConverterFactory;

    public ApiErrorAwareConverterFactory(
            EmptyJsonLenientConverterFactory emptyJsonLenientConverterFactory) {
        mEmptyJsonLenientConverterFactory = emptyJsonLenientConverterFactory;
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return mEmptyJsonLenientConverterFactory.requestBodyConverter(type, parameterAnnotations,
                methodAnnotations, retrofit);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        final Converter<ResponseBody, ?> delegateConverter =
                mEmptyJsonLenientConverterFactory.responseBodyConverter(type, annotations,
                        retrofit);
        return new Converter<ResponseBody, Object>() {
            @Override
            public Object convert(ResponseBody value) throws IOException {
                ResponseBody clone = RealResponseBody.create(value.contentType(), value.contentLength(),
                        value.source().buffer().clone());
                if (delegateConverter != null)
                    return delegateConverter.convert(value);

                return null;
            }
        };
    }
}

